package org.car.world.controller.shop;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.print.attribute.standard.RequestingUserName;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.car.world.common.util.BASE64DecodedMultipartFile;
import org.car.world.core.entily.AppTable;
import org.car.world.core.entily.MerchantsTable;
import org.car.world.core.entily.UserTable;
import org.car.world.service.AppService;
import org.car.world.service.MerchantsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;

import sun.misc.BASE64Decoder;

/**
 * @author Administrator
 * @ClassName: ShopController
 * @Description: 商户管理
 * @date Nov 20, 2018
 */
@Controller
@RequestMapping("shop")
public class ShopController {

    @Autowired
    MerchantsService merchantsService;

    @Autowired
    AppService appService;

    /**
     * @param @return 参数
     * @return String    返回类型
     * @throws
     * @Title: doshoplogin_init
     * @Description: 访问登陆
     */
    @RequestMapping("/")
    public String doshoplogin_init() {
        return "shop/login";
    }


    /**
     * @param @param  phone
     * @param @return 参数
     * @return String    返回类型
     * @throws
     * @Title: getMessage
     * @Description: 发送短信的方法
     */
    @ResponseBody
    @GetMapping("shopmessage")
    public String getMessage(@RequestParam(name = "phone", defaultValue = "") String phone) {
        // 短信应用SDK AppID
        int appid = 1400159342;
        // 短信应用SDK AppKey
        String appkey = "fc01a90c00259adf33241fdb3cd6aab2";
        // 需要发送短信的手机号码
        String[] phoneNumbers = {phone};
        // 短信模板ID，需要在短信应用中申请
        int templateId = 227801;
        //templateId7839对应的内容是"您的验证码是: {1}"
        // 签名
        String smsSign = "宋亚飞编程知识分享";
        int random = (int) ((Math.random() * 9 + 1) * 100000);
        Map<String, String> msg = new HashMap<String, String>(1);
        try {
            String[] params = {String.valueOf(random), "5"};
            SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
            SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumbers[0],
                    templateId, params, smsSign, "", "");
            System.out.println(result);
            msg.put("flag", "true");
            msg.put("code", String.valueOf(random));
        } catch (Exception e) {
            e.printStackTrace();
            msg.put("flag", "false");
        }
        return JSON.toJSONString(msg);
    }


    /**
     * @param @param  phone
     * @param @param  session
     * @param @return 参数
     * @return String    返回类型
     * @throws
     * @Title: phoneLogin
     * @Description: 登陆方法
     */
    @ResponseBody
    @GetMapping("shopphoneLogin")
    public String phoneLogin(@RequestParam(name = "phone") String phone, HttpSession session) {
        List<MerchantsTable> merlist = new ArrayList<MerchantsTable>();
        try {
            merlist = merchantsService.selectphone(phone);
            //merlist = merchantsService.selectphone("17630389495");
            if (merlist.size() < 0 || merlist == null) {
                //跳转到商家注册页面
            }
            session.setAttribute("Merchants", merlist);
            return "true";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "false";
    }


    /**
     * @param @param  phone
     * @param @param  session
     * @param @return 参数
     * @return String    返回类型
     * @throws
     * @Title: phoneLogin
     * @Description: 账号密码登陆方法
     */
    @ResponseBody
    @PostMapping("loginphpw")
    public boolean loginphpw(HttpSession session, MerchantsTable mer) {

        List<MerchantsTable> merlist = new ArrayList<MerchantsTable>();
        if (StringUtils.isEmpty(mer.getMerchantsPhone())) {
            return merchantsService.LoginPhonePwd(mer) > 0;
        } else {
            merlist = merchantsService.selectphone(mer.getMerchantsPhone());
            session.setAttribute("Merchants", merlist);
        }

        return merchantsService.LoginPhonePwd(mer) > 0;
    }


    /**
     * @param @param  page
     * @param @param  postion
     * @param @return 参数
     * @return String    返回类型
     * @throws
     * @Title: getNews
     * @Description: 新闻方法
     */
    @ResponseBody
    @GetMapping("news")
    public String getNews(@RequestParam(name = "page") Integer page, @RequestParam(name = "postion") String postion) {
        String text = "";
        try {
            InputStream is = new URL("http://api01.idataapi.cn:8000/news/qihoo?kw=" + postion + "&site=qq.com&apikey=YGt8JfL7NvczCWtjDE69o4LGuCJ3XMVIhoS7Qr0S781HtFJubK9cWidwco2nvugU&pageToken=" + page + "").openStream();
            try {
                BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
                StringBuilder sb = new StringBuilder();
                int cp;
                while ((cp = rd.read()) != -1) {
                    sb.append((char) cp);
                }
                text = sb.toString();
            } finally {
                is.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return text;
    }


    /**
     * @param @return 参数
     * @return String    返回类型
     * @throws
     * @Title: doshoplogin_init
     * @Description: 访问编辑
     */
    @RequestMapping("douserinfo")
    public String userinfo_init(@RequestParam(value = "phone", defaultValue = "", required = false) String phone, HttpSession session) {
        List<MerchantsTable> merlist = new ArrayList<MerchantsTable>();

        if (StringUtils.isEmpty(phone)) {
            merlist = (List<MerchantsTable>) session.getAttribute("Merchants");
            //merlist = merchantsService.selectphone("17630389495");
        } else {
            merlist = merchantsService.selectphone(phone);
        }
        session.setAttribute("Merchants", merlist);
        return "shop/userinfo";
    }


    /**
     * @param @param  mer
     * @param @return 参数
     * @return boolean    返回类型
     * @throws
     * @Title: update
     * @Description: 用户上传头像
     */
    @ResponseBody
    @RequestMapping("Base43Data")
    public Map<String, Object> dotesupdate(Integer id, String dataUrl, String fileType, HttpServletRequest request) {
        MerchantsTable record = new MerchantsTable();
        Map<String, Object> hashmap = new HashMap<String, Object>();

        if (StringUtils.isEmpty(dataUrl)) { // 图像数据为空
            hashmap.put("flag", false);
        } else {
            String filepath = BASE64DecodedMultipartFile.Base64UpdateFile(dataUrl, fileType, request);
            if (BASE64DecodedMultipartFile.FIlEFLAG == true) {
                record.setMerchantsId(id);
                record.setMerchantsActiv(filepath);
                boolean upactiv = merchantsService.updateByPrimaryIdActiv(record);
                if (upactiv) {
                    hashmap.put("flag", true);
                }
            }

        }
        return hashmap;
    }

    /**
     * @param @param  mer
     * @param @return 参数
     * @return boolean    返回类型
     * @throws
     * @Title: update
     * @Description: 执行更新方法
     */
    @ResponseBody
    @RequestMapping("updatemerchants")
    public boolean update(MerchantsTable mer, HttpSession session) {
        List<MerchantsTable> merlist = new ArrayList<MerchantsTable>();

        if (StringUtils.isEmpty(mer)) {
            return false;
        } else {
            SimpleDateFormat f = new SimpleDateFormat("hh:mm:ss");
            f.format(mer.getMerchantsBusiness());
            f.format(mer.getMerchantsEndtime());
            int flag = merchantsService.updateByPrimaryShop(mer);
            if (flag > 0) {
                merlist = merchantsService.selectphone(mer.getMerchantsPhone());
                session.removeAttribute("Merchants");
                session.setAttribute("Merchants", merlist);
                return true;
            }
            return false;
        }
    }


    /**
     * @param @param  session
     * @param @return 参数
     * @return String    返回类型
     * @throws
     * @Title: setting
     * @Description: 访问设置
     */
    @RequestMapping("setting")
    public String setting(HttpSession session) {
        List<MerchantsTable> merlist = new ArrayList<MerchantsTable>();
        StringBuffer sb = new StringBuffer();
        merlist = (List<MerchantsTable>) session.getAttribute("Merchants");
        //merlist = merchantsService.selectphone("17630389495");
        List<AppTable> appver = appService.selectbyversion();
        session.setAttribute("MerList", merlist);
        session.setAttribute("apptable", appver.get(0));
        return "shop/setting";
    }

    /**
     * @param @param  session
     * @param @return 参数
     * @return String    返回类型
     * @throws
     * @Title: setting
     * @Description: 退出登陆
     */
    @RequestMapping("dologin")
    public String outlogin(HttpSession session) {
        session.removeAttribute("Merchants");
        return "shop/login";
    }

}
